<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="主班老师" prop="mainTeacherId">
        <el-select
          class="!w-full"
          v-model="formData.mainTeacherId"
          clearable
          placeholder="请选择主班老师"
        >
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.teacherId"
            :label="teacher.teacherName"
            :value="teacher.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="助教老师" prop="assistantTeacherId">
        <el-select
          class="!w-full"
          v-model="formData.assistantTeacherId"
          clearable
          placeholder="请选择助教老师"
        >
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.teacherId"
            :label="teacher.teacherName"
            :value="teacher.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交班时间" prop="handoverTime">
        <template #label>
          <Tooltip message="可以不填，默认是当前时间" title="交班时间" />
        </template>
        <el-date-picker
          v-model="formData.handoverTime"
          type="datetime"
          value-format="x"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="HH:mm"
          :default-time="defaultTime1"
          :disabled-date="disabledDate"
          placeholder="选择交班时间"
        />
      </el-form-item>
      <el-form-item label="儿童数量" prop="childCount">
        <el-input-number
          v-model="formData.childCount"
          :min="0"
          clearable
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="情况说明" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入情况说明" />
      </el-form-item>
      <!-- <el-form-item label="附件。交班时拍的照片或视频" prop="filesUrls">
        <UploadFile v-model="formData.filesUrls" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ClassHandoverApi, ClassHandover } from '@/api/school/classAffairs/handover'
import { ClassesTeacherApi, ClassesTeacherVO } from '@/api/school/classes/teacher'

/** 班级每日交班 表单 */
defineOptions({ name: 'ClassHandoverForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  classId: 0,
  mainTeacherId: undefined,
  assistantTeacherId: undefined,
  handoverTime: undefined,
  childCount: undefined,
  remark: undefined,
  filesUrls: undefined
})
const formRules = reactive({
  classId: [{ required: true, message: '班级id不能为空', trigger: 'blur' }],
  mainTeacherId: [{ required: true, message: '主班老师不能为空', trigger: 'blur' }],
  assistantTeacherId: [{ required: true, message: '助教老师不能为空', trigger: 'blur' }],
  childCount: [{ required: true, message: '儿童数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const teacherList = ref([] as ClassesTeacherVO[]) // 年级教师列表

//禁用已经过去的时间
const disabledDate = (date) => {
  return date < new Date().setHours(0, 0, 0, 0)
}

//获取当前时间
function getCurrentTime() {
  const now = new Date()
  const nextHour = new Date(now)
  nextHour.setHours(now.getHours() + 0, 0, 0, 0) // 下一个小时的 00 分 00 秒 000 毫秒
  return nextHour
}

// 使用
const defaultTime1 = getCurrentTime()

/** 打开弹窗 */
const open = async (type: string, classId: number, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.classId = classId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ClassHandoverApi.getClassHandover(id)
    } finally {
      formLoading.value = false
    }
  }

  //查询当前班级关联的教师列表
  teacherList.value = await ClassesTeacherApi.getClassesTeacherList(classId)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ClassHandover
    if (formType.value === 'create') {
      await ClassHandoverApi.createClassHandover(data)
      message.success(t('common.createSuccess'))
    } else {
      await ClassHandoverApi.updateClassHandover(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    classId: 0,
    mainTeacherId: undefined,
    assistantTeacherId: undefined,
    handoverTime: undefined,
    childCount: undefined,
    remark: undefined,
    filesUrls: undefined
  }
  formRef.value?.resetFields()
}
</script>
